package com.hornsun.personnel.api;

import com.hornsun.config.ConfigInfo;
import com.hornsun.config.IRedisService;
import com.hornsun.data.constant.error.AccountError;
import com.hornsun.data.constant.error.CommonError;
import com.hornsun.data.constant.types.Whether;
import com.hornsun.data.dbo.*;
import com.hornsun.data.repository.AuthorizationRepository;
import com.hornsun.data.repository.ClientRepository;
import com.hornsun.personnel.dto.UpdateClientDTO;
import com.hornsun.role.service.RoleService;
import com.hornsun.util.DESUtil;
import com.hornsun.util.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by 编译中... on 2018/7/10.
 */
@RestController
@RequestMapping("/api/personnel")
public class PersonnelAPI {

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private AuthorizationRepository authorizationRepository;

    @Autowired
    private ConfigInfo configInfo;

    @Autowired
    private RoleService roleService;

    @Autowired
    private IRedisService service;




    @GetMapping("/getInfo")
    public ResponseEntity<?> getClients(){
        return new ResponseEntity<Object>(clientRepository.getTotal(), HttpStatus.OK);
    }


    @Transactional
    @PostMapping("/permission/deleteClient")
    public ResponseEntity<?> deleteClient( String[] guids){
        if (guids==null){
            return new ResponseEntity<Object>(HttpStatus.OK);
        }
        int deleteFailed = 0;
        for (int i=0;i<guids.length;i++){
            Client client = clientRepository.getByGuid(guids[i]);
            if(client==null){
                deleteFailed++;
                continue;
            }
            if (roleService.whetherSuper(client.getRoleGuid())){
                deleteFailed++;
                continue;
            }
            if (client.getWhetherAuth()==Whether.YES.getType().intValue()){
                Authorization authorization = authorizationRepository.getByGuid(client.getClientGuid());
                if ((authorization.getOfflineTime()>0)&&service.isKeyExists(configInfo.getRedisAccount(),client.getAccount())){
                    byte[] clientInfoBytes = (byte[]) service.get(configInfo.getRedisAccount(),client.getAccount());
                    ClientInfo clientInfo = (ClientInfo) SerializeUtils.deSerialize(clientInfoBytes);
                    if (clientInfo!=null){
                        List<OfflineInfo> offlineInfoList = clientInfo.getOfflineInfoList();
                        List<AccountInfo> accountInfoList = clientInfo.getAccountInfoList();
                        if (offlineInfoList.size()!=0){
                            deleteFailed++;
                            continue;
                        }
                        if (accountInfoList.size()!=0){
                            Date now = new Date();
                            if (now.getTime()-accountInfoList.get(0).getTime().getTime()>12*1000){
                                deleteFailed++;
                                continue;
                            }
                        }
                    }
                }
                service.remove(configInfo.getRedisAccount(),client.getAccount());
                authorizationRepository.delete(guids[i]);
            }
            clientRepository.deleteByGuid(guids[i]);
        }
        if (deleteFailed>0){
            return new ResponseEntity<Object>(CommonError.FAILED.getCode(),HttpStatus.OK);
        }
        return new ResponseEntity<Object>(clientRepository.getTotal(),HttpStatus.OK);
    }

    @Transactional
    @PostMapping("/permission/addClient")
    public ResponseEntity<?> addClient(Client client) throws Exception {
        if (client==null){
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        }
        if (client.getName()==null||client.getAccount()==null||client.getDepartmentId()==null||client.getRoleGuid()==null){
            return new ResponseEntity<Object>(CommonError.NOT_EXIST.getCode(),HttpStatus.OK);
        }
        if (client.getName().getBytes("utf-8").length>16){
            return new ResponseEntity<Object>(AccountError.NAME_TOO_LONG.getCode(),HttpStatus.OK);
        }
        String regex ="^[a-zA-Z\\d]{6,16}$";
        if (!client.getAccount().matches(regex)){
            return new ResponseEntity<Object>(AccountError.ACCOUNT_FORMAT_ERROR.getCode(),HttpStatus.OK);
        }

        if (configInfo.getSuperRoleGuid().equals(client.getRoleGuid())){
            return new ResponseEntity<Object>(AccountError.IS_SUPER.getCode(),HttpStatus.OK);
        }

        if (clientRepository.accountExist(client.getAccount())){
            return new ResponseEntity<Object>(CommonError.HAS_EXIST.getCode(),HttpStatus.OK);
        }

        client.setClientGuid(UUID.randomUUID().toString());
        client.setWhetherAuth((byte)Whether.NOT.getType().intValue());
        client.setCreateTime(new Date());
        String desPassword = DESUtil.encrypt(configInfo.getInitialPassword());
        client.setPassword(desPassword);
        clientRepository.addClient(client);
        return new ResponseEntity<Object>(clientRepository.getTotal(),HttpStatus.OK);
    }

    @PostMapping("/permission/updateClient")
    public ResponseEntity<?> updateClient(UpdateClientDTO updateClientDTO) {
        if (updateClientDTO.getClientGuid() == null) {
            return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
        }
        Client client = new Client();
        client.setClientGuid(updateClientDTO.getClientGuid());
        client.setName(updateClientDTO.getName());
        client.setDepartmentId(updateClientDTO.getDepartmentId());
        client.seteMail(updateClientDTO.geteMail());
        client.setPhone(updateClientDTO.getPhone());
        client.setRoleGuid(updateClientDTO.getRoleGuid());
        clientRepository.updateClient(client);
        return new ResponseEntity<Object>(clientRepository.getTotal(), HttpStatus.OK);
    }


}
